package b3d.parsers
{
	import b3d.core.Object3D;
	import b3d.geometry.Mesh3D;
	import b3d.materials.AmbientLightMaterial;
	
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.registerClassAlias;
	import flash.utils.ByteArray;
	import flash.utils.getTimer;

	public class Parser_b3dx extends BaseParser
	{
		private var data			:ByteArray;		
		
		public function Parser_b3dx(){}			
		
		public override function parseFromUrl(url:String, onParseComplete:Function):void
		{
			this.url 				= url;
			this.onParseComplete 	= onParseComplete;
			var loader:URLLoader 	= new URLLoader(new URLRequest(url));
			loader.dataFormat 		= URLLoaderDataFormat.BINARY;
			
			loader.addEventListener(Event.COMPLETE, onLoadComplete);	
		}
		private function onLoadComplete(e:Event):void
		{
			var data:ByteArray = (e.target as URLLoader).data;
			parseFromData(data);
		}
		public function parseFromData(data:ByteArray):void
		{
			this.data = data;
			//data.endian = Endian.LITTLE_ENDIAN;
			var time:int = getTimer();
			data.position = 0;
			data.uncompress();
			
			mesh = new Mesh3D();
			mesh.vertices = parseFloats();
			mesh.uvs = parseFloats();
			mesh.normals = parseFloats();
			mesh.ids  = parseUints();			
			
			trace("parse time", getTimer()-time);
			
			objects = new Vector.<Object3D>();
			var object:Object3D = new Object3D().build(mesh, new AmbientLightMaterial(Math.random()*0xFFFFFF));
			objects.push(object);
			
			if(onParseComplete != null) onParseComplete();
		}
		public function parseFloats():Vector.<Number>
		{
			var num:int = data.readInt();
			var floats:Vector.<Number> = new Vector.<Number>(num, true);
			var i:int;
			while(i < num)
			{
				floats[i] = data.readFloat();
				i++;
			}
			return floats;
		}
		public function parseUints():Vector.<uint>
		{
			var num:int = data.readInt();
			var uints:Vector.<uint> = new Vector.<uint>(num, true);
			var i:int;
			while(i < num)
			{
				uints[i] = data.readUnsignedInt();
				i++;
			}
			return uints;
		}
	}
}